package com.lengyu.iottransfer.gateway.schedules;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lengyu.iottransfer.gateway.common.BasePageParamDto;
import com.lengyu.iottransfer.gateway.common.ByteUtils;
import com.lengyu.iottransfer.gateway.config.MqttSendGateway;
import com.lengyu.iottransfer.gateway.dto.MqttDeviceCurrentDto;
import com.lengyu.iottransfer.gateway.entity.DeviceTransfer;
import com.lengyu.iottransfer.gateway.influxdb.service.impl.DeviceLogInfluxService;
import com.lengyu.iottransfer.gateway.redis.RedisUtils;
import com.lengyu.iottransfer.gateway.service.IDeviceTransferService;
import com.lengyu.iottransfer.gateway.service.impl.CarBeiDouGPSService;
import com.lengyu.iottransfer.gateway.tcp.daxiang.DaxiangGuanpianTransfer;
import com.lengyu.iottransfer.gateway.tcp.sanyuanShuibiao.SanyuanTransfer;
import net.bytebuddy.matcher.FilterableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class ComputerRoomMonitorSchedule {


    private final static Logger logger = LoggerFactory.getLogger(ComputerRoomMonitorSchedule.class);

    @Autowired
    RedisUtils redisUtils;

    @Resource
    private MqttSendGateway mqttSendGateway;

    @Autowired
    IDeviceTransferService deviceTransferService;

    @Autowired
    DeviceLogInfluxService deviceLogInfluxService;

    @Autowired
    CarBeiDouGPSService carBeiDouGPSService;

    /**
     * 每小时执行一次
     * @throws InterruptedException
     */
    @Scheduled(cron = "0 0 */1 * * ?")
//    @Scheduled(fixedDelay = 1000 * 60 * 5)
    public void  sendReadCommand() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("type","LCD_ELEC_USER_GATEWAY");
        List<DeviceTransfer> deviceTransferList = deviceTransferService.list(queryWrapper);
        if(deviceTransferList != null && deviceTransferList.size() > 0){
            for(DeviceTransfer deviceTransfer:deviceTransferList){
                String[] deviceArray = deviceTransfer.getCode().split("MN");
                String subAddr = deviceArray[1];

                String command = getLCDQueryCommand(subAddr);
                logger.info("发送内容：" + command);
                logger.info("发送TOPIC：" + deviceTransfer.getGatewayReceiveTopic());
                mqttSendGateway.sendToMqtt(deviceTransfer.getGatewayReceiveTopic(), ByteUtils.hexStrToByteArray(command));
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    logger.error("ex",e);
                }
            }
        }


        sendMttCommandToZQ();
    }


    /**
     * 每2分钟查询一次设备当前状态
     * @throws InterruptedException
     */
//    @Scheduled(cron = "0 0 */1 * * ?")
    @Scheduled(fixedDelay = 1000 * 60 * 2 )
    public void  getCarGPSSchedule() {
        JSONObject currentData = carBeiDouGPSService.getGPSLocationByPlate("14164474497");
        List<MqttDeviceCurrentDto> mqttDeviceCurrentDtoList = carBeiDouGPSService.convertToMqttDeviceCurrentDto(currentData.getJSONArray("data"));
        if(mqttDeviceCurrentDtoList != null && mqttDeviceCurrentDtoList.size() > 0){
//            logger.info("转换之后的信息：" + JSONObject.toJSONString(mqttDeviceCurrentDtoList));
            mqttDeviceCurrentDtoList.forEach(j->{
                //发送消息到自己平台
                mqttSendGateway.sendToMqtt(deviceTransferService.getIotPlatPropertyTopicV1("JINTU_CAR_GPS") , JSONObject.toJSONString(j));
                logger.info("发送mqtt完成：TOPIC:" + deviceTransferService.getIotPlatPropertyTopicV1("JINTU_CAR_GPS") +"  PAYLOAD:"+ JSONObject.toJSONString(j));
            });
        }

    }
    /**
     * 发送到电表的读取命令,电能数据
     * //地址码+ 功能码+数据码+校验码
     * @return
     */
    public static String getHexSendInfo1(){
//        StringBuilder sb = new StringBuilder();
//        //设备地址 1-124之间
//        sb.append("01").append(" ");
//        //功能码03
//        sb.append("03").append(" ");
//
//        //数据码---start
////        //寄存器地址高位
////        sb.append("10").append(" ");
////        //寄存器地址低位
////        sb.append("3D").append(" ");
//
//        //寄存器地址高位
//        sb.append("00").append(" ");
//        //寄存器地址低位
//        sb.append("1D").append(" ");
//
//        //寄存器个数高位
//        sb.append("00").append(" ");
//        //寄存器个数低位
//        sb.append("02").append(" ");
//
//        //数据码---end
//        //校验码---start
//        String crc16 = ByteUtils.getCRC16(sb.toString(),true);
//        sb.append(crc16);
//        //校验码---end
        return getLCDQueryCommand("01");
    }

    /**
     * 发送到电表的读取命令,电能数据
     * //地址码+ 功能码+数据码+校验码
     * @return
     */
    public static String getLCDQueryCommand(String addr){
        StringBuilder sb = new StringBuilder();
        //设备地址 1-124之间
        sb.append(addr).append(" ");
        //功能码03
        sb.append("03").append(" ");

        //数据码---start
//        //寄存器地址高位
//        sb.append("10").append(" ");
//        //寄存器地址低位
//        sb.append("3D").append(" ");

        //寄存器地址高位
        sb.append("00").append(" ");
        //寄存器地址低位
        sb.append("1D").append(" ");

        //寄存器个数高位
        sb.append("00").append(" ");
        //寄存器个数低位
        sb.append("02").append(" ");

        //数据码---end
        //校验码---start
        String crc16 = ByteUtils.getCRC16(sb.toString(),true);
        sb.append(crc16);
        //校验码---end
        return sb.toString();
    }

    /**
     * 发送到电表的读取命令,电能数据
     * //地址码+ 功能码+数据码+校验码
     * @return
     */
    public static String getHexSendInfo2(){
        StringBuilder sb = new StringBuilder();
        //设备地址 1-124之间
        sb.append("01").append(" ");
        //功能码03
        sb.append("03").append(" ");

        //数据码---start
        //寄存器地址高位
        sb.append("10").append(" ");
        //寄存器地址低位
        sb.append("00").append(" ");

        //寄存器个数高位
        sb.append("00").append(" ");
        //寄存器个数低位
        sb.append("25").append(" ");

        //数据码---end
        //校验码---start
        String crc16 = ByteUtils.getCRC16(sb.toString(),true);
        sb.append(crc16);
        //校验码---end
        return sb.toString();
    }

    /**
     * 每次执行停止5s继续执行
     * @throws InterruptedException
     */
    @Scheduled(fixedDelay = 60000)
    public void  sendAlarmMessageSchedule() {
//        String hexStr = "7FFFFFFFFFFFFFFF";
//        byte[] byteArray = ByteUtils.hexStrToByteArray(hexStr);
//        ByteBuffer buffer = ByteBuffer.wrap(byteArray);
//        long num = buffer.getLong();
//        System.out.println("转换后的long数字为: " + num);
//        DaxiangGuanpianTransfer ls = new DaxiangGuanpianTransfer();
//        byte[] test = ByteUtils.hexStrToByteArray("ce ce a0 01 30 32 00 01 fe 20 00 0f ff 70 00 00 00 00 00 0a 24 8c c2");
//        ls.transforToMqttData(test);
//        byte[] test = ByteUtils.hexStrToByteArray("fa fa a0 01 30 32 00 06 00 12 00 64 00" +
//                " 65 00 64 00 01 00 01 ff ff ff ff ff ff 00 01 11 c7");
//        processReadResult(test);
//        BasePageParamDto basePageParamDto = new BasePageParamDto();
//        JSONObject paramJson = new JSONObject();
//        paramJson.put("deviceCode","dxgp_a00130320006");
//        paramJson.put("msgType","deviceReport");
//        List<Long> timeList = new ArrayList<>();
//        timeList.add(1722355200000L);
//        timeList.add(1722441600000L);
//        paramJson.put("time",timeList);
//        basePageParamDto.setParamMapObj(paramJson);
//        deviceLogInfluxService.page(basePageParamDto);
    }
    private String processReadResult(byte[] byteArray) {
        try{
            logger.info("预埋传感器读命令返回消息 ");
            //网关
            String gatewayNum = ByteUtils.byteArrayToHexString(byteArray,2,2,false);
            //节点
            String nodeNum = ByteUtils.byteArrayToHexString(byteArray,4,2,false);
            //传感器
            String monitorNum = ByteUtils.byteArrayToHexString(byteArray,6,2,false);
            String deviceCode = "ymcgq"+ "_"+gatewayNum +nodeNum + monitorNum;
            String mingling = ByteUtils.byteArrayToHexString(byteArray,8,1,false);
            //数据长度
            int dataLength = ByteUtils.byteToInt(byteArray[9]);
            JSONObject resultJson= new JSONObject();
            if(dataLength/2 > 0){
                for(int i=0;i<dataLength/2;i++){
                    int tmpData = ByteUtils.byteArrayToShort(byteArray,10 + 2*i);
                    resultJson.put("data" + i,tmpData);
                }
            }
            if(dataLength == 10*2){
                logger.info("预埋传感器读命令返回消息："+deviceCode + "数据长度：" + dataLength + "预埋传感当前状态：" + JSONObject.toJSONString(resultJson));
            }
            else if(dataLength == 9){
                logger.info("预埋传感器读命令返回消息："+deviceCode + "数据长度：" + dataLength + "预埋传感器参数1：" + JSONObject.toJSONString(resultJson));
            }
            else if(dataLength == 4){
                logger.info("预埋传感器读命令返回消息："+deviceCode + "数据长度：" + dataLength + "预埋传感器参数2：" + JSONObject.toJSONString(resultJson));
            }

            return "";
        }
        catch (Exception ex){
            logger.error("error",ex);
            return "";
        }

    }
    /**
     * 发送命令铁建工科获取蒸汽表记信息
     */
    private void sendMttCommandToZQ(){
        String command = "01 03 00 01 00 14 14 05";
//        String command = "01 03 00 13 00 02 35 CE";
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("type","F2001XA3L1C4R2PWAL1VAC");
        List<DeviceTransfer> deviceTransferList = deviceTransferService.list(queryWrapper);
        if(deviceTransferList != null && deviceTransferList.size() > 0){
            for(DeviceTransfer deviceTransfer:deviceTransferList){
                logger.info("铁建工科气表发送获取信息命令：" + command);
                logger.info("发送TOPIC：" + deviceTransfer.getGatewayReceiveTopic());
                mqttSendGateway.sendToMqtt(deviceTransfer.getGatewayReceiveTopic(), ByteUtils.hexStrToByteArray(command));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    logger.error("ex",e);
                }
            }
        }
    }

}
